package com.loan.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.loan.common.core.domain.PageQuery;
import com.loan.common.core.domain.model.LoginUser;
import com.loan.common.core.page.TableDataInfo;
import com.loan.common.helper.LoginHelper;
import com.loan.common.utils.DateUtils;
import com.loan.common.utils.StringUtils;
import com.loan.system.domain.ApplyEntity;
import com.loan.system.domain.CompanyEntity;
import com.loan.system.domain.ExamineOverDataEntity;
import com.loan.system.domain.IncomeExpendDetailEntity;
import com.loan.system.mapper.ApplyMapper;
import com.loan.system.mapper.IncomeExpendDetailMapper;
import com.loan.system.service.CompanyService;
import com.loan.system.service.IncomeExpendDetailService;
import lombok.RequiredArgsConstructor;
import org.omg.CORBA.IMP_LIMIT;
import org.redisson.api.RMap;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
@RequiredArgsConstructor
public class IncomeExpendDetailServiceImpl implements IncomeExpendDetailService {

    private final CompanyService companyService;

    private final IncomeExpendDetailMapper baseMapper;

    private final ApplyMapper applyMapper;

    /**
     * 获取分页列表
     *
     * @param beginTime
     * @param endTime
     * @param pageQuery
     * @return
     */
    @Override
    public TableDataInfo<Map<String, Object>> selectPageList(String channel, Long companyId, String beginTime, String endTime, PageQuery pageQuery) {
        companyId = ObjectUtil.isNotNull(LoginHelper.getCompanyId()) ? LoginHelper.getCompanyId() : companyId;
        Integer pageNum = (pageQuery.getPageNum() - 1) * pageQuery.getPageSize();
        List<IncomeExpendDetailEntity> list = baseMapper.selectIncomeExpendList(companyId, channel, beginTime, endTime, pageNum, pageQuery.getPageSize());
        int count = baseMapper.selectIncomeExpendCount(companyId, channel, beginTime, endTime);
        List<Map<String, Object>> mapList = new ArrayList<>(pageQuery.getPageSize());
        for (IncomeExpendDetailEntity entity : list) {
            Map<String, Object> map = new HashMap<>();
            //获取放款笔数
            int applyNum = applyMapper.selectApplyNum(entity.getBuildDate(), channel, companyId, null, null);
            map.put("num", applyNum);
            //获取首逾数
            int firstOverNum = applyMapper.selectFirstOverNumByBuildDate(entity.getBuildDate(), channel, companyId, null, null);
            map.put("firstNum", firstOverNum);
            //逾期数
            long overNum = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                    .eq(ObjectUtil.isNotNull(companyId), "company_id", companyId)
                    .eq(StringUtils.isNotBlank(channel), "channel", channel)
                    .eq("status", "8")
                    .between("apply_time", DateUtils.toBeginDateByDay(entity.getBuildDate()), DateUtils.toEndDateByDay(entity.getBuildDate()))
            );
            map.put("overNum", overNum);
            long repayNum = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                    .eq(ObjectUtil.isNotNull(companyId), "company_id", companyId)
                    .eq(StringUtils.isNotBlank(channel), "channel", channel)
                    .eq("status", "7")
                    .between("apply_time", DateUtils.toBeginDateByDay(entity.getBuildDate()), DateUtils.toEndDateByDay(entity.getBuildDate()))
            );
            map.put("repapyNum", repayNum);
            long repayMoney = applyMapper.selectRepayMoneyByDate(entity.getBuildDate(), channel, companyId, null, null);
            map.put("repayMoney", repayMoney);
            map.put("buildDate", entity.getBuildDate());
            map.put("whiteNum", entity.getWhiteNum());
            map.put("applyMoney", entity.getOrderMoney());
            map.put("money", entity.getOrderCapital());
            mapList.add(map);
        }
        Page<Map<String, Object>> page = new Page<>();
        page.setRecords(mapList);
        page.setTotal(count);
        return TableDataInfo.build(page);


//        Integer pageNum = (pageQuery.getPageNum() - 1) * pageQuery.getPageSize();
//        List<Map<String, Object>> list = applyMapper.selectIncomeExpendList(companyId, channel, beginTime, endTime, pageNum, pageQuery.getPageSize());
//        int count = applyMapper.selectIncomeExpendCount(companyId, channel, beginTime, endTime);
//        Page<Map<String, Object>> page = new Page<>();
//        page.setRecords(list);
//        page.setTotal(count);
//        return TableDataInfo.build(page);
    }

    @Override
    public List<Map<String, Object>> selectTotal(String channel, Long companyId, String beginTime, String endTime) {
//        return applyMapper.selectIncomeExpendTotal(companyId, channel, beginTime, endTime);
        companyId = ObjectUtil.isNotNull(LoginHelper.getCompanyId()) ? LoginHelper.getCompanyId() : companyId;
        IncomeExpendDetailEntity entity = baseMapper.selectIncomeExpendTotal(companyId, channel, beginTime, endTime);
        Map<String, Object> map = new HashMap<>();
        //获取放款笔数
        int applyNum = applyMapper.selectApplyNum(null, channel, companyId, beginTime, endTime);
        map.put("num", applyNum);
        //获取首逾数
        int firstOverNum = applyMapper.selectFirstOverNumByBuildDate(null, channel, companyId, beginTime, endTime);
        map.put("firstNum", firstOverNum);
        //逾期数
        long overNum = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                .eq(ObjectUtil.isNotNull(companyId), "company_id", companyId)
                .eq(StringUtils.isNotBlank(channel), "channel", channel)
                .eq("status", "8")
                .between(StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime), "apply_time", DateUtils.toBeginDateByDay(beginTime), DateUtils.toEndDateByDay(endTime))
        );
        map.put("overNum", overNum);
        long repayNum = applyMapper.selectCount(new QueryWrapper<ApplyEntity>()
                .eq(ObjectUtil.isNotNull(companyId), "company_id", companyId)
                .eq(StringUtils.isNotBlank(channel), "channel", channel)
                .eq("status", "7")
                .between(StringUtils.isNotBlank(beginTime) && StringUtils.isNotBlank(endTime), "apply_time", DateUtils.toBeginDateByDay(beginTime), DateUtils.toEndDateByDay(endTime))
        );
        map.put("repapyNum", repayNum);
        long repayMoney = applyMapper.selectRepayMoneyByDate(null, channel, companyId, beginTime, endTime);
        map.put("repayMoney", repayMoney);
        map.put("whiteNum", entity.getWhiteNum());
        map.put("applyMoney", entity.getOrderMoney());
        map.put("money", entity.getOrderCapital());

        List<Map<String, Object>> list = new ArrayList<>();
        list.add(map);
        return list;
    }

    /**
     * 每日凌晨生成当日公司初始数据
     */
    @Override
    public void incomeExpendDetailData() {
        List<CompanyEntity> companyEntities = companyService.selectList();
        String buildDate = DateUtils.dateTimeNow(DateUtils.YYYY_MM_DD);
        for (CompanyEntity entity : companyEntities) {
            List<Map<String, Object>> list = applyMapper.selectListByCompanyIdAndDate(entity.getId(), buildDate);
            if (!CollectionUtils.isEmpty(list)) {
                for (Map<String, Object> map : list) {
                    IncomeExpendDetailEntity incomeExpendDetail = baseMapper.selectOne(new QueryWrapper<IncomeExpendDetailEntity>()
                            .eq("build_date", buildDate)
                            .eq("company_id", entity.getId())
                            .eq(ObjectUtil.isNotNull(map.get("channel")) && StringUtils.isNotBlank(map.get("channel").toString()), "channel", map.get("channel"))
                    );
                    if (ObjectUtil.isNull(incomeExpendDetail)) {
                        incomeExpendDetail = new IncomeExpendDetailEntity();
                        incomeExpendDetail.setCreateTime(new Date());
                    }
                    incomeExpendDetail.setBuildDate(buildDate);
                    incomeExpendDetail.setCompanyId(entity.getId());
                    incomeExpendDetail.setChannel(map.get("channel") != null ? map.get("channel").toString() : null);
//            //获取该平台当日的白户数
//            long num = applyMapper.selectCount(new QueryWrapper<ApplyEntity>().eq("company_id", entity.getId()).between("apply_time", DateUtils.toBeginDateByDay(buildDate), DateUtils.toEndDateByDay(buildDate)));
                    incomeExpendDetail.setWhiteNum(Integer.valueOf(map.get("whiteUser").toString()));
                    incomeExpendDetail.setWhiteOrderNum(Integer.valueOf(map.get("whiteUser").toString()));
//            //获取该平台当日放款本金和合同金额
//            Map<String, Object> map = applyMapper.selectApplyMoneyByCompanyIdAndDate(entity.getId(), buildDate);
                    incomeExpendDetail.setOrderCapital(Long.valueOf(map.get("money1").toString()));
                    incomeExpendDetail.setOrderMoney(Long.valueOf(map.get("money").toString()));
                    incomeExpendDetail.setUpdateTime(new Date());
                    baseMapper.insertOrUpdate(incomeExpendDetail);
                }
            } else {
                IncomeExpendDetailEntity incomeExpendDetail = baseMapper.selectOne(new QueryWrapper<IncomeExpendDetailEntity>()
                        .eq("build_date", buildDate)
                        .eq("company_id", entity.getId())
                );
                if (ObjectUtil.isNull(incomeExpendDetail)) {
                    incomeExpendDetail = new IncomeExpendDetailEntity();
                    incomeExpendDetail.setCreateTime(new Date());
                }
                incomeExpendDetail.setBuildDate(buildDate);
                incomeExpendDetail.setCompanyId(entity.getId());
                incomeExpendDetail.setOrderMoney(0L);
                incomeExpendDetail.setWhiteOrderNum(0);
                incomeExpendDetail.setOrderCapital(0L);
                incomeExpendDetail.setWhiteNum(0);
                incomeExpendDetail.setUpdateTime(new Date());
                baseMapper.insertOrUpdate(incomeExpendDetail);
            }
        }
    }

    @Override
    public IncomeExpendDetailEntity selectByCompanyIdAndDate(Long companyId, String buildDate) {
        return baseMapper.selectOne(new QueryWrapper<IncomeExpendDetailEntity>()
                .eq("company_id", companyId)
                .eq("build_date", buildDate)
        );
    }

    @Override
    public void updateWhiteById(IncomeExpendDetailEntity entity) {
        baseMapper.updateWhiteById(entity);
    }

    @Override
    public void save(IncomeExpendDetailEntity entity) {
        baseMapper.insert(entity);
    }
}
